package com.zcsy.manage.web.base;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.ManageConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestContext;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CommonCollectAccount;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.DistrictInfo;
import com.zcsy.manage.model.system.Role;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICommonCollectAccountService;
import com.zcsy.manage.service.base.ICommonConfigService;
import com.zcsy.manage.service.common.CommonService;
import com.zcsy.manage.service.company.IDistributionCompanyService;
import com.zcsy.manage.service.company.IOperationCompanyService;
import com.zcsy.manage.service.company.IPropertyCompanyService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IDistrictInfoService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.web.common.LogUtils;

@Controller
@RequestMapping(value = "/cellInfo")
public class CellInfoController {
	@Autowired
	private ICellInfoService cellInfoService;
	
	@Autowired
	private IDistrictInfoService districtInfoService;
	
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private IOperationCompanyService operationCompanyService;
	
	@Autowired
	private IPropertyCompanyService propertyCompanyService;
	
	@Autowired
	private IDistributionCompanyService distributionCompanyService;

	@Autowired
	private IDictService dictService;
	
	@Autowired
    private ICommonCollectAccountService commonCollectAccountService;
	
	@Autowired
    private ICommonConfigService commonConfigService;
	
    /**
     * @Description 返回小区信息查询列表<br>
     * 
     * @param model 
     * @param pNo 当前页面
     * @param cellName 小区名称
     * @param req 用户请求
     * @return 返回小区信息查询列表
     * @author caiyinli 13277030520@163.com
     * @date 2016年3月29日
     * @see 
     */
    @RequestMapping(value="cellInfoList" , method = RequestMethod.GET)
    public String cellInfoList(Model model, Integer pNo, Integer pSize, String cellName, HttpServletRequest req){
    	
	    if(pNo == null){
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        
        CellInfo cellInfo = new CellInfo();
        
        if(StringUtils.isNotEmpty(cellName)){
        	cellInfo.setCellName(cellName);
        }
   
        List<CellInfo> cellInfos = cellInfoService.selectByKeyword(cellInfo);
        PageInfo<CellInfo> info = new PageInfo<CellInfo>(cellInfos);
        
		model.addAttribute("cellInfo", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("cellName", cellName);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "base/cellinfo/cellInfoList";
    }
    
    /**
     * @Description 返回新增或编辑小区页面<br>
     * type = 1:新增页面
     * type = 2:编辑页面
     * 
     * @param model
     * @param id 主键id id=0新增 ；id!=0编辑
     * @return 返回新增或编辑小区页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年3月30日
     * @see 
     */
    @RequestMapping(value = "editCellInfo", method = RequestMethod.GET)
    public String selectById(Model model, String id) {
        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.SAVE_TYPE);
            } else {
                CellInfo cellInfo = cellInfoService.selectByPrimaryKey(id);
                if(cellInfo != null){
                	model.addAttribute("type", Constants.EDIT_TYPE);
                	model.addAttribute("cellInfo", cellInfo);
                	model.addAttribute("districtList", districtInfoService.getDistrictInfoByParentId(cellInfo.getCityId()));
                	model.addAttribute("cityList", districtInfoService.getDistrictInfoByParentId(cellInfo.getProvinceId()));
                	
                	List<String> list = cellInfoService.getMenusByCellId(id, Constants.SYSTEM_OWNER);
                	if(list != null && list.size() > 0){
                		StringBuffer buffer = new StringBuffer();
                		for(String item : list){
                			buffer.append(item + ",");
                		}
                		
                		String menus = buffer.substring(0, buffer.length() - 1);
                		model.addAttribute("selmenus", menus);
                	}
                }
            }
            
            List<CommonCollectAccount> accounts = commonCollectAccountService.getAll();
            model.addAttribute("accounts", accounts);
            
            model.addAttribute("provinceList",districtInfoService.getDistrictInfoByLevel((int)Constants.MENU_LEVEL_FIREST));
            model.addAttribute("operationCompanys", operationCompanyService.getAllCompany());
            model.addAttribute("propertyCompanys", propertyCompanyService.getAllCompany());
            model.addAttribute("distributionCompanys", distributionCompanyService.getAllCompany());
        } catch (Exception e) {
        }
        return "base/cellinfo/cellInfoEdit";
    }
    
    /**
     * @Description 保存和更新小区方法<br>
     * cellId不为空且不为0，则表示更新
     * 否则表示保存
     * @param cellName 小区名称
     * @param provinceName 省
     * @param cityName 市
     * @param areaName 区
     * @param cellAddress 详细地址
     * @param areaLand 土地面积
     * @param areaConstruction 建筑面积
     * @param container 图文混排描述
     * @param cellId 小区信息主键id
     * @param request 用户请求
     * @param response 服务器响应
     * @return 1：成功  ; 0:失败
     * @author caiyinli 13277030520@163.com
     * @date 2016年3月30日
     * @see 
     */
    @RequestMapping(value = "saveOrUpdateCellInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveCellInfo(String cellName, Integer provinceId, Integer cityId, Integer areaId, String cellAddress,
    		String operationCompanyId , String proCompanyId, String disCompanyId , BigDecimal areaLand, BigDecimal areaConstruction,
    		Integer sort, String container,String cellId,BigDecimal longitude, BigDecimal latitude,String logo, String[] menus,HttpServletRequest request,HttpServletResponse response) {
        RequestJson result = new RequestJson();
        User user = CommonService.getSessionUser();
        try {
        	CellInfo record = new CellInfo();
            record.setCellName(cellName);
            record.setProvinceId(provinceId);
            record.setCityId(cityId);
            record.setAreaId(areaId);
            record.setCellAddress(cellAddress);
            record.setAreaLand(areaLand);
            record.setAreaConstruction(areaConstruction);
            record.setCellDescription(container);
            record.setSort(sort);
            record.setUserAccount(user.getLoginname());
            
            record.setLongitude(longitude);
            record.setLatitude(latitude);
            
            record.setOperationCompanyId(operationCompanyId);
            record.setProCompanyId(proCompanyId);
            record.setDisCompanyId(disCompanyId);
            record.setLogo(logo);
        
            // 检验名称是否存在
            boolean isUpdate = (cellId != ""&& !"0".equals(cellId));
            boolean nameExists = cellInfoService.isNameExists(isUpdate ? cellId : null, cellName);
            if(nameExists) {
                result.setSuccess(false);
                result.setMsg("小区名称已存在");
            } else {
                
                DistrictInfo pDistrictInfo = districtInfoService.getDistrictInfoById(provinceId);
                record.setProvinceName(pDistrictInfo.getRegionName());
                DistrictInfo cDistrictInfo = districtInfoService.getDistrictInfoById(cityId);
                record.setCityName(cDistrictInfo.getRegionName());
                DistrictInfo aDistrictInfo = districtInfoService.getDistrictInfoById(areaId);
                record.setAreaName(aDistrictInfo.getRegionName());
                
                if(cellId != ""&& !"0".equals(cellId)){
                    record.setId(cellId);
                    record.setUpdateTime(new Date());
                    cellInfoService.update(record);
                    LogUtils.insertLog("用户编辑小区信息", user.getId(), request);
                }else{
                    record.setId(UniqueNumberUtils.get18UniqueNumber());
                    cellInfoService.insert(record);
                    
                    String cellID = record.getId();
                    /*********默认小区配置**********/
                    commonConfigService.insert(Constants.CELL_CONFIG, "小区客服1", "cell_service_phone1", "", cellID);
                    commonConfigService.insert(Constants.CELL_CONFIG, "小区客服2", "cell_service_phone2", "", cellID);
                    
                    /*********默认物业配置**********/
                    commonConfigService.insertValueOfInteger(Constants.PROPERTY_CONFIG, "最低缴费月数", "property_min_month", Constants.STATE_ENABLED, cellID);
                    commonConfigService.insertValueOfInteger(Constants.PROPERTY_CONFIG, "物业结账时间", "property_feebill_paytime", Constants.STATE_ENABLED, cellID);
                    commonConfigService.insert(Constants.PROPERTY_CONFIG, "物业费说明", "property_feebill_memo", "", cellID);
                    commonConfigService.insert(Constants.PROPERTY_CONFIG, "物业发票说明", "property_billtype_memo", "", cellID);
                    commonConfigService.insert(Constants.PROPERTY_CONFIG, "停车费说明", "car_feebill_memo", "", cellID);
                    commonConfigService.insert(Constants.PROPERTY_CONFIG, "停车费发票说明", "car_billtype_memo", "", cellID);
                    commonConfigService.insertValueOfInteger(Constants.PROPERTY_CONFIG, "停车费是否可缴费（对应房屋欠物业费时）", "car_if_pay", Constants.STATE_ENABLED, cellID);
                    
                    LogUtils.insertLog("用户新增小区信息和小区配置信息", user.getId(), request);
                }
                
                cellInfoService.updateCellMenu(record.getId(), menus);
            }
            
        }catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("操作异常");
        }
        
        return result;
    }
    
    /**
     * @Description 批量删除小区信息<br>
     * 备注：删除之前判断是否有依赖，即其他地方关联了该小区，有的话就不能删除
     * @param cellIDs 需要被删除的小区id集合
     * @param req 用户请求
     * @return 1：成功  0：失败
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value = "deleteCellInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deletePage(String cellIDs,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = CommonService.getSessionUser();
        try {
			String ids[] = cellIDs.split("\\,");
			for (int i = 0; i < ids.length; i++ ) {
				CellInfo cellInfo = cellInfoService.selectByPrimaryKey(ids[i]);
				if(cellInfo != null){
					//角色小区关联数目
					int roleCellCount = roleService.selectCountByCellId(ids[i]);
					/*TODO 
					 * 因为暂时还没确定是否用查询表的方式检查是否有关联，故此处遗留一点问题，到时需一并解决
					 * 出现的问题是：当可以删除和不可以删除的小区一起删除时，提示的是最后一个要被删除的小区的消息，
					 * 		即如果最后一个可以删除，不论前面如何，显示的为删除成功,如果最后一个不可以删除，前面的可以删除的都删除掉了，但返回的是最后一个小区被引用的消息
					 * 建议更改方案：将id不用循环的方式分开来删除，查关联数目，直接把多个小区id的String传入数据库来查，如果都没有就全部删除，有的话就提示有小区被引用
					 * 弊端：由于查询是全部一起查的，故用户看不到是哪一个小区被引用
					*/
					if(cellInfo.getIsUsed() == Constants.IS_USED || roleCellCount > 0){
						result.setMsg(cellInfo.getCellName()+"小区已被引用，不能删除!");
						result.setSuccess(false);
					}else{
						cellInfoService.deleteByPrimaryKey(ids[i]);
						result.setSuccess(true);
						LogUtils.insertLog("用户删除小区信息", user.getId(), req);
					}
				}
			}
			
		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        return result;
    }
    
    
    /** 
     * @Title: getRMenu 
     * @Description: 菜单权限编辑页面
     * @param @param model 模型
     * @param @param roleId 角色ID
     * @param @param req 请求REQUEST
     * @return String JSP页面路径
     * @throws 
     */
    @RequestMapping(value = "queryAllCellInfo", method = RequestMethod.GET)
    public String queryAllCellInfo(Model model, String rId, String cells,@Context HttpServletRequest req) {
    	List<String> list = new ArrayList<String>();
    	
    	if(StringUtils.isEmpty(cells)){
    		if(rId != null && !"0".equals(rId) ){
                //取到当前与角色关联的所有小区
                list = roleService.getCellIdListByRoleId(rId);
        	}
        	model.addAttribute("cellList", list);
        }else{
        	model.addAttribute("cellList", "[" + cells + "]");
        }
        
        return "system/role/roleCell";
    }
    
    @RequestMapping(value="treeData" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson treeData(HttpServletRequest req,HttpServletResponse response){
        RequestJson result = new RequestJson();
        JSONArray jsonArr=new JSONArray();
        try {
            List<CellInfo> list = cellInfoService.getAllCellInfo();
            Set<Map<String, String>> listcell = new HashSet<Map<String,String>>();
            List<CellInfo> userCell = CommonService.getSessionUser().getCellInfos();
            
            for(CellInfo item : list){
            	Map<String, String> mapcell = new HashMap<String, String>();
            	mapcell.put("id", item.getId());
            	mapcell.put("pId", item.getCityId().toString());
            	mapcell.put("name", item.getCellName());
            	mapcell.put("chkDisabled", "true");
            	
            	//当前用户自己有权限的小区才可选中
            	for(CellInfo j : userCell){
            		if(j.getId().equals(item.getId())){
            			mapcell.put("chkDisabled", "false");
            			break;
            		}
            	}
            	
            	Map<String, String> mapcity = new HashMap<String, String>();
            	Map<String, String> mapprovince = new HashMap<String, String>();
            	
            	listcell.add(mapcell);
            	
            	mapcity.put("id", item.getCityId().toString());
            	mapcity.put("pId", item.getProvinceId().toString());
            	mapcity.put("name", item.getCityName());
            	
            	listcell.add(mapcity);
            	
            	mapprovince.put("id", item.getProvinceId().toString());
            	mapprovince.put("pId", "0");
            	mapprovince.put("name", item.getProvinceName());
            	
            	listcell.add(mapprovince);
            	
            }
            
            for(Map<String, String> item : listcell){
            	JSONObject json = new JSONObject();
            	json.put("id", item.get("id"));
            	json.put("pId", item.get("pId"));
            	json.put("name", item.get("name"));
            	json.put("chkDisabled", item.get("chkDisabled"));
            	jsonArr.add(json);
            }
            
            result.setObj(jsonArr.toJSONString());
        }catch (Exception e) {
           result.setMsg("操作异常");
           result.setSuccess(false);
        }
        return result;
    }
    
    @RequestMapping(value = "saveOrUpdateRoleCell", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateRoleCell(@RequestParam(value="cells[]") String[] cells,String roleId,String roleName,String descrip,int roleType,int isAllCell, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
    		Role role = new Role();
    		role.setRoleName(roleName);
    		role.setDescrip(descrip);
    		role.setRoleType(roleType);
    		role.setIsAllCell(isAllCell);
    		
    		int flag = Constants.SQL_RESULT_ERROR;
    		if(roleId != "" && !"0".equals(roleId)){
    			role.setId(roleId);
    			flag = roleService.updateByPrimaryKey(role);
    		}else{
    			role.setId(UniqueNumberUtils.get18UniqueNumber());
    			flag = roleService.insert(role);
    		}
    			if(flag == Constants.SQL_RESULT_SUCCESS){
    				result.setSuccess(true);
    				if(isAllCell == ManageConstants.NOT_ALL_CELL){
    					roleService.updateRoleCell(roleId, cells);
    				}else{
    					List<CellInfo> list = cellInfoService.getAllCellInfo();
    					String[] cell = new String[list.size()];
    					int count = list.size();
    					for (int i = 0; i < count; i++) {
    						cell[i] = list.get(i).getId();
						}
    					roleService.updateRoleCell(roleId, cell);
    				}
    			}
        	
            result.setSuccess(true);
            result.setObj(RequestContext.getSession().getAttribute(RequestConstants.USER_SESSION_ID));
        } catch (Exception e) {
            result.setMsg("操作异常");
        }
        return result;
    }
    
    /**
     * @Description 小区管理信息详情
     * @author fangli Fanglwj520@163.com
     * @date 2016年5月17日
     * @see
     */
    @RequestMapping(value = "/cellInfodetail", method = RequestMethod.GET)
    public String cellInfoDetail(Model model, String id, HttpServletRequest req){
        try {
            CellInfo cellInfo = cellInfoService.selectByPrimaryKey(id);
            if(cellInfo != null){
                model.addAttribute("cellInfo", cellInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return "base/cellinfo/cellinfoDetail";
    }

    
	/**
	 * @Description 根据排序实现置顶功能，即修改当前排序为最大排序值加1，并且更新修改时间<br>
	 * 
	 * @param id 商品id
	 * @param req 用户请求
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月3日
	 * @see 
	 */
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id,HttpServletRequest req){
        RequestJson result = new RequestJson();
        User user = CommonService.getSessionUser();
        try {
        	CellInfo cellInfo = cellInfoService.selectByPrimaryKey(id);
        	if(cellInfo != null){
        		cellInfo.setUpdateTime(DateUtils.getDate());
        		cellInfoService.updateSort(cellInfo);
        		LogUtils.insertLog("用户置顶小区", user.getId(), req);
        	}
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }
	
	@RequestMapping(value = "getCellMenu", method = RequestMethod.GET)
    public String getCellMenu(Model model,@QueryParam("cellId") String cellId,@QueryParam("menus") String menus, @Context HttpServletRequest req) {
        try {
            if(cellId != null && !"0".equals(cellId) ){
            	//取到当前与角色关联的所有菜单
            	CellInfo cell = cellInfoService.selectByPrimaryKey(cellId);
                model.addAttribute("cell", cell);
            }
            
            model.addAttribute("userType", Constants.OWNER_TYPE);
            if(org.springframework.util.StringUtils.isEmpty(menus)){
            	List<String> list = cellInfoService.getMenusByCellId(cellId, Constants.SYSTEM_OWNER);
                model.addAttribute("menuList", list);
            }else{
            	model.addAttribute("menuList", "[" + menus + "]");
            }
            
        } catch (Exception e) {
        }
        return "base/cellinfo/cellMenu";
    }
}
